<template>
  <div class="login-page">
    <!-- 背景装饰 -->
    <div class="bg-decoration"></div>
    <el-row justify="center" class="content-box">
      <el-col :span="22" :md="18" :lg="16">
        <el-row class="login-container">
          <!-- 左侧品牌区域 -->
          <el-col :span="24" :md="11" class="login-left">
            <div class="brand-box">
              <div class="brand-logo" @click="goHome">
                <el-icon :size="60">
                  <Logo></Logo>
                </el-icon>
                <h1 class="brand-name">云校园</h1>
              </div>
              <div class="brand-slogan">
                连接校园，分享生活，交流学习，共创美好校园生活
              </div>
              <div class="features">
                <div class="feature-item">
                  <el-icon :size="24" class="feature-icon">
                    <UserFilled></UserFilled>
                  </el-icon>
                  <div class="feature-text">
                    <h3>加入社区</h3>
                    <p>与来自全国各高校的学生交流</p>
                  </div>
                </div>

                <div class="feature-item">
                  <el-icon :size="24" class="feature-icon">
                    <IconBook></IconBook>
                  </el-icon>
                  <div class="feature-text">
                    <h3>学习交流</h3>
                    <p>分享学习经验，解决学术难题</p>
                  </div>
                </div>
                <div class="feature-item">
                  <el-icon :size="24" class="feature-icon">
                    <Bell></Bell>
                  </el-icon>
                  <div class="feature-text">
                    <h3>校园资讯</h3>
                    <p>获取最新校园动态和活动信息</p>
                  </div>
                </div>
              </div>
              <div class="copyright">
                <p>重庆外语外事学院</p>
                <p>软件工程 专升本03班</p>
              </div>
            </div>
          </el-col>

          <!-- 右侧表单区域 -->
          <el-col :span="24" :md="13" class="login-right">
            <div class="form-container">
              <!-- 切换按钮 -->
              <el-button
                  class="toggle-button"
                  @click="target = target === 'login' ? 'enroll' : 'login'"
              >
                {{ target === 'login' ? '注册账号' : '已有账号？登录' }}
                <el-icon class="toggle-icon">
                  <Right></Right>
                </el-icon>
              </el-button>

              <!-- 表单切换动画 -->
              <transition name="form-swap" mode="out-in">
                <!-- 登录表单 -->
                <div v-if="target === 'login'" class="form-content">
                  <div class="form-header">
                    <h2 class="form-title">欢迎回来</h2>
                    <p class="form-subtitle">请登录你的账号继续使用</p>
                  </div>

                  <el-form
                      size="large"
                      :model="loginForm"
                      ref="loginFormRef"
                      :rules="loginRules"
                      class="login-form"
                  >
                    <el-form-item prop="account">
                      <el-input
                          v-model="loginForm.account"
                          placeholder="账号/手机号"
                          :prefix-icon="UserFilled"
                          class="custom-input"
                      />
                    </el-form-item>

                    <el-form-item prop="password">
                      <el-input
                          v-model="loginForm.password"
                          type="password"
                          placeholder="密码"
                          show-password
                          :prefix-icon="Lock"
                          class="custom-input"
                      />
                    </el-form-item>

                    <el-form-item prop="captcha" class="captcha-group">
                      <el-input
                          v-model="loginForm.captcha"
                          placeholder="验证码"
                          :prefix-icon="Key"
                          class="custom-input captcha-input"
                      />
                      <div class="captcha-image">
                        <img
                            :src="captchaUrl"
                            alt="验证码"
                            @click="refreshCaptcha"
                            class="captcha-img"
                        >
                      </div>
                    </el-form-item>

                    <div class="form-actions">
                      <el-checkbox v-model="isRemember" class="remember-checkbox">
                        记住我 30 天
                      </el-checkbox>
                      <a href="#" class="forgot-password">忘记密码?</a>
                    </div>
                  </el-form>

                  <el-button
                      class="submit-button"
                      style="width: 100%"
                      v-loading="loading"
                      @click="submitLogin(loginFormRef)"
                  >
                    登录
                  </el-button>

                  <!-- 第三方登录 -->
                  <div class="third-party-login">
                    <div class="divider">
                      <span class="divider-text">其他登录方式</span>
                    </div>
                    <div class="social-buttons">
                      <el-button class="social-btn wechat">
                        <el-icon :size="20" color="white">
                          <IconWeChat/>
                        </el-icon>
                      </el-button>
                      <el-button class="social-btn qq">
                        <el-icon :size="20">
                          <IconQQ/>
                        </el-icon>
                      </el-button>
                      <el-button class="social-btn weibo">
                        <el-icon :size="20" color="white">
                          <IconWeibo/>
                        </el-icon>
                      </el-button>
                    </div>
                  </div>
                </div>
                <!-- 注册表单 -->
                <div v-else class="form-content">
                  <div class="form-header">
                    <h2 class="form-title">快速注册</h2>
                    <p class="form-subtitle">填写以下信息完成注册</p>
                  </div>
                  <el-form
                      size="large"
                      :model="enrollForm"
                      ref="enrollFormRef"
                      :rules="enrollRules"
                      class="register-form"
                  >
                    <el-form-item prop="userName">
                      <el-input
                          v-model="enrollForm.userName"
                          placeholder="用户名"
                          :prefix-icon="UserFilled"
                          class="custom-input"
                      />
                    </el-form-item>

                    <el-form-item prop="password">
                      <el-input
                          v-model="enrollForm.password"
                          type="password"
                          placeholder="密码（至少6位）"
                          show-password
                          :prefix-icon="Lock"
                          class="custom-input"
                      />
                    </el-form-item>

                    <el-form-item prop="phone">
                      <el-input
                          v-model="enrollForm.phone"
                          placeholder="手机号码"
                          :prefix-icon="Phone"
                          class="custom-input"
                      />
                    </el-form-item>

                    <el-form-item prop="captcha" class="captcha-group">
                      <el-input
                          v-model="enrollForm.captcha"
                          placeholder="验证码"
                          :prefix-icon="Key"
                          class="custom-input captcha-input"
                      />
                      <el-button
                          class="get-captcha-btn"
                          @click="getCaptchaCode"
                          :disabled="countdown > 0"
                      >
                        {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
                      </el-button>
                    </el-form-item>
                  </el-form>

                  <el-button
                      class="submit-button"
                      style="width: 100%"
                      @click="submitEnroll(enrollFormRef)"
                  >
                    注册
                  </el-button>

                  <p class="register-agreement">
                    点击注册即表示同意我们的
                    <a href="#" class="agreement-link">用户协议</a>
                    和
                    <a href="#" class="agreement-link">隐私政策</a>
                  </p>
                </div>
              </transition>
            </div>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <!-- 页脚 -->
    <footer class="login-footer">
      <div class="footer-content">
        <p>© 2025 云校园 版权所有</p>
        <div class="footer-links">
          <a href="#">用户协议</a>
          <a href="#">隐私政策</a>
          <a href="#">帮助中心</a>
        </div>
      </div>
    </footer>
  </div>
</template>

<script lang="ts" setup>
import {
  UserFilled,
  Lock,
  Right,
  Bell,
  Key,
  Phone
} from "@element-plus/icons-vue";
import {reactive, ref, onMounted} from "vue";
import {useRouter} from "vue-router";
import {useUserStore} from "@/stores/user";
import type {FrontUserLoginDTO} from "@/api/front/user/type";
import {reqEnrollUser} from "@/api/front/user";
import type {FormInstance} from "element-plus";
import {reqCaptcha, reqGetPhoneCaptcha} from "@/api";
import { useWebSocket } from '@/composables/useWebSocket';

// 路由和状态管理
const router = useRouter();
const userStore = useUserStore();
const { init: initWebSocket } = useWebSocket();

// 响应式数据
let loading = ref(false);
let isRemember = ref(false);
let loginFormRef = ref<FormInstance>();
let enrollFormRef = ref<FormInstance>();
let target = ref('login');
let countdown = ref(0);
let captchaUrl = ref('');

// 表单数据
let loginForm = reactive<FrontUserLoginDTO & { captcha: string }>({
  account: "",
  password: "",
  captcha: "",
  captchaId: ""
});

let enrollForm = reactive({
  userName: "",
  password: "",
  phone: "",
  captcha: "",
});

// 初始化验证码
const refreshCaptcha = async () => {
  loginForm.captcha = ''
  let res = await reqCaptcha()
  captchaUrl.value = res.data.captchaImage;
  loginForm.captchaId = res.data.captchaKey;
};

// 获取手机验证码
const getCaptchaCode = async () => {
  // 1. 验证手机号是否为空
  if (!enrollForm.phone) {
    return;
  }
  // 2. 验证手机号格式
  return new Promise((resolve) => {
    enrollFormRef.value?.validateField('phone', async (errorMessage) => {
      if (!errorMessage) {
        return resolve(false);
      }
      try {
        // 3. 发送获取验证码请求
        const res = await reqGetPhoneCaptcha(enrollForm.phone);
        // 4. 处理响应（根据实际API调整）
        if (res.code === 200) {
          enrollForm.captcha = res.data.captcha;
          // 开始倒计时
          startCountdown();
          return resolve(true);
        } else {
          console.log('获取验证码失败:', res)
          return resolve(false);
        }
      } catch (error) {
        console.error('请求失败:', error);
        return resolve(false);
      }
    });
  });
};

// 倒计时函数（单独封装）
const startCountdown = () => {
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};

// 登录提交
let submitLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      await userStore.userLogin(loginForm);
      //建立ws连接
      initWebSocket()
      router.push("/");
      loading.value = false;
    } else {
      console.log('登录表单验证失败', fields);
    }
  });
};

// 注册提交
let submitEnroll = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 调用注册接口
      reqEnrollUser(enrollForm).then(() => {
        // 注册成功后切换到登录
        target.value = 'login';
      });
    } else {
      console.log('注册表单验证失败', fields);
    }
  });
};
let goHome = () => {
  router.push('/');
}

// 表单验证规则
let loginRules = reactive({
  account: [
    {required: true, message: "请输入用户名或手机号", trigger: "blur"},
    {min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur"}
  ],
  password: [
    {required: true, message: "请输入密码", trigger: "blur"},
    {min: 3, max: 20, message: "密码长度不能少于6位", trigger: "blur"}
  ],
  captcha: [
    {required: true, message: "请输入验证码", trigger: "blur"},
  ]
});

let enrollRules = reactive({
  userName: [
    {required: true, message: "请输入用户名", trigger: "blur"},
    {min: 3, max: 16, message: "用户名长度在 3 到 16 个字符", trigger: "blur"}
  ],
  password: [
    {required: true, message: "请输入密码", trigger: "blur"},
    {min: 6, max: 20, message: "密码长度不能少于6位", trigger: "blur"}
  ],
  phone: [
    {required: true, message: "请输入手机号码", trigger: "blur"},
    {pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur"}
  ],
  captcha: [
    {required: true, message: "请输入验证码", trigger: "blur"},
    {min: 6, max: 6, message: "验证码长度为6位", trigger: "blur"}
  ]
});

// 初始化
onMounted(() => {
  refreshCaptcha();
});
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  background-color: #f8fafc;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}

/* 背景装饰 */
.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  background: radial-gradient(circle at 10% 20%, rgba(79, 134, 198, 0.05) 0%, transparent 20%),
  radial-gradient(circle at 90% 70%, rgba(79, 134, 198, 0.05) 0%, transparent 30%);
}

.content-box {
  flex: 1;
  padding: 2rem 1rem;
  position: relative;
  z-index: 1;
}

.login-container {
  background: #ffffff;
  border-radius: 1rem;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

/* 左侧品牌区域 */
.login-left {
  background: linear-gradient(135deg, #4F86C6 0%, #3A6BB3 100%);
  color: white;
  padding: 2rem;
  display: flex;
  align-items: center;
}

.brand-box {
  width: 100%;
}

.brand-logo {
  display: flex;
  align-items: center;
  margin-bottom: 2rem;
}

.brand-name {
  font-size: 2rem;
  font-weight: bold;
  margin-left: 0.75rem;
}

.brand-slogan {
  font-size: 1rem;
  opacity: 0.9;
  margin-bottom: 3rem;
  line-height: 1.6;
}

.features {
  display: flex;
  flex-direction: column;
  gap: 2rem;
  margin-bottom: 3rem;
}

.feature-item {
  display: flex;
  align-items: flex-start;
}

.feature-icon {
  background-color: rgba(255, 255, 255, 0.15);
  padding: 0.75rem;
  border-radius: 50%;
  margin-right: 1rem;
  flex-shrink: 0;
}

.feature-text h3 {
  font-size: 1.1rem;
  margin-bottom: 0.25rem;
  font-weight: 600;
}

.feature-text p {
  font-size: 0.9rem;
  opacity: 0.8;
}

.copyright {
  font-size: 0.85rem;
  opacity: 0.7;
  margin-top: auto;
  line-height: 1.6;
}

/* 右侧表单区域 */
.login-right {
  padding: 2rem;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-container {
  width: 100%;
  max-width: 350px;
}

.toggle-button {
  width: 100%;
  background-color: #f0f5ff;
  color: #4F86C6;
  border: none;
  margin-bottom: 2rem;
  padding: 0.75rem;
  font-weight: 500;
  transition: all 0.3s ease;
}

.toggle-button:hover {
  background-color: #e6f0ff;
  color: #3A6BB3;
  transform: translateY(-2px);
}

.toggle-icon {
  margin-left: 0.5rem;
  transition: transform 0.3s ease;
}

.toggle-button:hover .toggle-icon {
  transform: translateX(3px);
}

.form-header {
  text-align: center;
  margin-bottom: 2rem;
}

.form-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.5rem;
}

.form-subtitle {
  color: #64748b;
  font-size: 0.9rem;
}

.login-form, .register-form {
  width: 100%;
  margin-bottom: 1.5rem;
}

.custom-input {
  border-radius: 0.5rem;
  border-color: #e2e8f0;
  height: 50px;
  transition: all 0.3s ease;
}

.custom-input:focus {
  border-color: #4F86C6;
  box-shadow: 0 0 0 3px rgba(79, 134, 198, 0.1);
}

.captcha-group {
  display: flex;
  gap: 0.75rem;
}

.captcha-input {
  flex: 1;
}

.captcha-image {
  width: 128px;
  height: 50px;
}

.captcha-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 0.5rem;
  cursor: pointer;
  border: 1px solid #e2e8f0;
  transition: all 0.2s ease;
}

.captcha-img:hover {
  border-color: #cbd5e1;
}

.get-captcha-btn {
  width: 128px;
  height: 50px;
  border-radius: 0.5rem;
  background-color: #f8fafc;
  color: #4F86C6;
  border-color: #e2e8f0;
  transition: all 0.3s ease;
}

.get-captcha-btn:hover:not(:disabled) {
  background-color: #f0f5ff;
  border-color: #bfdbfe;
}

.get-captcha-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  font-size: 0.9rem;
}

.remember-checkbox {
  color: #64748b;
}

.forgot-password {
  color: #4F86C6;
  text-decoration: none;
  transition: color 0.2s ease;
}

.forgot-password:hover {
  color: #3A6BB3;
  text-decoration: underline;
}

.submit-button {
  background-color: #4F86C6;
  border-color: #4F86C6;
  color: white;
  height: 50px;
  border-radius: 0.5rem;
  font-weight: 500;
  transition: all 0.3s ease;
}

.submit-button:hover {
  background-color: #3A6BB3;
  border-color: #3A6BB3;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(79, 134, 198, 0.2);
}

/* 第三方登录 */
.third-party-login {
  margin-top: 2rem;
}

.divider {
  display: flex;
  align-items: center;
  margin-bottom: 1.5rem;
}

.divider::before,
.divider::after {
  content: "";
  flex: 1;
  height: 1px;
  background-color: #e2e8f0;
}

.divider-text {
  padding: 0 1rem;
  font-size: 0.85rem;
  color: #94a3b8;
}

.social-buttons {
  display: flex;
  justify-content: center;
  gap: 1rem;
}

.social-btn {
  width: 42px;
  height: 42px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  border: none;
}

.social-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.wechat {
  background-color: #07c160;
  color: white;
}

.qq {
  background-color: #1296db;
  color: white;
}

.weibo {
  background-color: #e6162d;
  color: white;
}

/* 注册相关样式 */
.register-agreement {
  font-size: 0.8rem;
  color: #94a3b8;
  text-align: center;
  margin-top: 1.5rem;
  line-height: 1.5;
}

.agreement-link {
  color: #4F86C6;
  text-decoration: none;
}

.agreement-link:hover {
  text-decoration: underline;
}

/* 表单切换动画 */
.form-swap-enter-active,
.form-swap-leave-active {
  transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
}

.form-swap-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.form-swap-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

/* 页脚样式 */
.login-footer {
  padding: 1.5rem 0;
  border-top: 1px solid #e2e8f0;
  margin-top: 2rem;
}

.footer-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.75rem;
}

.footer-content p {
  font-size: 0.85rem;
  color: #94a3b8;
}

.footer-links {
  display: flex;
  gap: 1.5rem;
}

.footer-links a {
  font-size: 0.85rem;
  color: #94a3b8;
  text-decoration: none;
  transition: color 0.2s ease;
}

.footer-links a:hover {
  color: #4F86C6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-left {
    display: none;
  }

  .login-container {
    box-shadow: none;
  }

  .login-right {
    padding: 1.5rem;
  }

  .brand-mobile {
    display: flex;
    justify-content: center;
    margin-bottom: 1.5rem;
  }
}
</style>
